< previous page page_191 next page >

Page 191
Getting Rid of Spaces
In Listing 9.5, you used InStr to find the first space in a person's name, assuming that it was the space between the first and middle name. Most long strings contain spaces in the middle of the string, which are necessary for proper spacing of words, paragraphs, and so on. However, you also may end up with spaces at the beginning or end of your strings, which often are unwanted spaces. These spaces typically occur when the user accidentally types a space at the beginning or end of a text field. They also show up when you are using a fixed-length string and the number of characters in the string do not fill the available space.
For example, the following calls to the Len() function each return a different number:
Print Len("Hello, world!")

Print Len("   Hello, world!")

Print Len("Hello, world!   ")
Most of the time, spaces don't do any harm except take up a little memory. However, when you combine strings or try to take action based on their content, unwanted spaces can cause all kinds of problems. For example, suppose you have two 30-character text boxes for first and last names. A user could inadvertently type three characters of text and then a bunch of spaces. If you need to concatenate the first and last name for a mailing label, the extra spaces are included. However, Visual Basic provides some string "trimming" functions to eliminate the trailing spaces.
To get rid of the spaces at the end of a string, you can use one of these Visual Basic functions:
LTrimRemoves the spaces from the beginning of a string
RTrimRemoves the spaces from the end of string
TrimRemoves the spaces from both the beginning and end of a string
Each of these functions uses a similar syntax; you've already seen an example in Listing 9.5. The code in the following lines shows how to use the Trim function to remove the spaces in a mailing label example:
picMail.Print Trim(FirstName) & " " & Trim(LastName)
picMail.Print Trim(Address)
picMail.Print Trim(City) & ", " & Trim(State) & "  " & Trim(Zip)
Replacing Characters in a String
Now let me add a little confusion to your life. You just saw how the Mid function retrieves a piece of a string from the middle of a source string. The same keyword, Mid, is used to replace a part of a string. However, the syntax is quite different, in that you use the function on the left-hand side of an assignment statement in this case. When it is used to replace characters in a string, it is referred to as the Mid statement.
The Mid statement replaces part of one string with another string by using the following syntax:
Mid(sourcestr, startpos[, numchars]) = replstr

 
< previous page page_191 next page >